<template>
	<view class="container">
		<!-- 顶部标签页导航 -->
		<view class="tabs-container">
			<!-- Logo -->
			<view class="logo">
				<img src="../../static/teamEmblem2.png" alt="Logo" class="logo-image" />
			</view>
			<view class="tab" v-for="(tab, index) in tabs" :key="index" :class="{ active: activeTab === index }"
				@click="switchTab(index)">
				<text class="tab-icon">
					<image src="/static/icon/DOC.svg" mode=""></image>
				</text>
				<text class="tab-title">{{ tab.title }}</text>
				<text class="tab-close" @click.stop="closeTab(index)">×</text>
			</view>
			<view class="new-tab" @click="addTab">+</view>
		</view>

		<!-- 搜索栏和操作按钮 -->
		<view class="toolbar">
			<view class="search-container">
				<text class="search-icon">
					<image src="/static/icon/search.svg" mode="	widthFix" class=""></image>
				</text>
				<input class="search-input" placeholder="在此处进行搜索……" v-model="searchQuery" />
			</view>
			<view class="toolbar-buttons">
				<button class="toolbar-button" @click="createNewFolder">新建文件夹</button>
				<button class="toolbar-button" @click="download">下载</button>
				<button class="toolbar-button" style="background-color: #4CAF50;" @click="upload">上传</button>
				<button class="toolbar-button" @click="toggleDisplayMode">
					{{ getCurrentTab().displayMode === 'grid' ? '列表视图' : '网格视图' }}
				</button>
			</view>
		</view>

		<!-- 新建文件夹重命名弹窗 -->
		<view v-if="showRenameDialog" class="rename-dialog-overlay">
			<view class="rename-dialog" @click.stop>
				<text class="dialog-title">新建文件夹</text>
				<input v-model="newFolderName" class="dialog-input" @keyup.enter="confirmRename" />
				<view class="dialog-buttons">
					<button class="dialog-button" @click="cancelRename">取消</button>
					<button class="dialog-button confirm" @click="confirmRename">确定</button>
				</view>
			</view>
		</view>
		<!-- 重命名 -->
		<!-- 		<view v-if="showRenameDialog" class="rename-dialog-overlay">
			<view class="rename-dialog" @click.stop>
				<text class="dialog-title">新建文件夹</text>
				<input v-model="newFolderName" class="dialog-input" @keyup.enter="confirmRename" />
				<view class="dialog-buttons">
					<button class="dialog-button" @click="cancelRename">取消</button>
					<button class="dialog-button confirm" @click="confirmRename">确定</button>
				</view>
			</view>
		</view> -->
		<!-- 主内容区 -->
		<view class="main-content">
			<!-- 左侧文件目录 -->
			<view class="sidebar">
				<!-- 递归渲染文件夹结构 -->
				<template v-for="folder in folders" :key="folder.id">
					<view class="folder-item-wrapper">
						<view class="folder-item" @click.stop="toggleFolder(folder)" @dblclick="openFolderById(folder.id)">
							<text v-if="folder.children && folder.children.length > 0" class="expand-icon">
								{{ folder.isExpanded ? '▼' : '▶' }}
							</text>
							<text v-else class="indent"></text>
							<text class="folder-icon">📁</text>
							<text class="folder-name">{{ folder.name }}</text>
						</view>
						<!-- 递归渲染子文件夹 -->
						<view v-if="folder.children && folder.children.length > 0 && folder.isExpanded" class="subfolders">
							<template v-for="subfolder in folder.children" :key="subfolder.id">
								<view class="folder-item-wrapper">
									<view class="folder-item" @click.stop="toggleFolder(subfolder)"
										@dblclick="openFolderById(subfolder.id)">
										<text class="indent"></text>
										<text class="folder-icon">📁</text>
										<text class="folder-name">{{ subfolder.name }}</text>
									</view>
								</view>
							</template>
						</view>
					</view>
				</template>
			</view>

			<!-- 中间文件展示区域 -->
			<view class="file-display">
				<!-- 面包屑导航 -->
				<view class="breadcrumb">
					<text class="breadcrumb-item" @click="navigateToRoot">首页</text>
					<text v-for="(item, index) in getCurrentTab().currentPath" :key="index">
						<text> / </text>
						<text class="breadcrumb-item" @click="navigateToPath(index)">{{ item }}</text>
					</text>
				</view>

				<!-- 文件列表 -->
				<!-- 网格视图 -->
				<view v-if="getCurrentTab().displayMode === 'grid'" class="file-grid">
					<!-- 文件夹 -->
					<view class="file-item" v-for="(folder, index) in getCurrentTab().currentFolder.folders"
						:key="'folder-' + index" @click="handleItemClick(folder, 'folder')"
						@dblclick="handleItemDblClick(folder, 'folder')"
						:class="{ selected: getCurrentTab().selectedFile && getCurrentTab().selectedFile.id === folder.id }">
						<view class="file-icon-large">📁</view>
						<text class="file-name">{{ folder.name }}</text>
					</view>
					<!-- 文件 -->
					<view class="file-item" v-for="(file, index) in getCurrentTab().currentFolder.files" :key="'file-' + index"
						@click="handleItemClick(file, 'file')" @dblclick="handleItemDblClick(file, 'file')"
						:class="{ selected: getCurrentTab().selectedFile && getCurrentTab().selectedFile.id === file.id }">
						<view class="file-icon-large">{{ getFileIcon(file.type) }}</view>
						<text class="file-name">{{ file.name }}</text>
						<button class="download-btn" @click.stop="downloadFile(file)">下载</button>
						<text class="file-size">{{ formatSize(file.size) }}</text>
					</view>
				</view>

				<!-- 列表视图 -->
				<view v-else-if="getCurrentTab().displayMode === 'list'" class="file-list">
					<!-- 列表标题行 -->
					<view class="list-header">
						<view class="list-header-cell name-cell">名称</view>
						<view class="list-header-cell type-cell">类型</view>
						<view class="list-header-cell size-cell">大小</view>
						<!-- <view class="list-header-cell download-cell">下载</view> -->
						<view class="list-header-cell date-cell">修改日期</view>
					</view>

					<!-- 文件夹 -->
					<view class="list-item" v-for="(folder, index) in getCurrentTab().currentFolder.folders"
						:key="'folder-' + index" @click="handleItemClick(folder, 'folder')"
						@dblclick="handleItemDblClick(folder, 'folder')"
						:class="{ selected: getCurrentTab().selectedFile && getCurrentTab().selectedFile.id === folder.id }">
						<view class="list-cell name-cell">
							<view class="file-icon-small">📁</view>
							<text>{{ folder.name }}</text>
						</view>
						<view class="function-cell">
							<!-- <button class="download-btn"></button> -->
							<button class="delete-btn" @click.stop="deleteFolder(folder)"></button>
							<button class="rename-btn" @click.stop="renameFolder(folder)"></button>
						</view>
						<view class="list-cell type-cell">文件夹</view>
						<view class="list-cell size-cell">—</view>
						<!-- <view class="list-cell download-cell"></view> -->
						<view class="list-cell date-cell">{{ folder.updatedAt ? formatDate(folder.updatedAt) : '' }}</view>
					</view>

					<!-- 文件 -->
					<view class="list-item" v-for="(file, index) in getCurrentTab().currentFolder.files" :key="'file-' + index"
						@click="handleItemClick(file, 'file')" @dblclick="handleItemDblClick(file, 'file')"
						:class="{ selected: getCurrentTab().selectedFile && getCurrentTab().selectedFile.id === file.id }">
						<view class="list-cell name-cell">
							<view class="file-icon-small">{{ getFileIcon(file.type) }}</view>
							<text>{{ file.name }}</text>
						</view>
						<view class="function-cell">
							<button class="download-btn" @click.stop="downloadFile(file)"></button>
							<button class="delete-btn" @click.stop="deleteFile(file)"></button>
							<button class="rename-btn" @click.stop="renameFile(file)"></button>
						</view>
						<view class="list-cell type-cell">{{ getExtensionFromMimeType(file.name) }}</view>
						<view class="list-cell size-cell">{{ formatSize(file.size) }}</view>
						<!-- 						<view class="list-cell download-cell">
							<button class="download-btn-small" @click.stop="downloadFile(file)">下载</button>
						</view> -->
						<view class="list-cell date-cell">{{ file.modifiedDate }}</view>
					</view>
				</view>

				<!-- 文件详情（当选中文件时显示） -->
				<view v-if="getCurrentTab().displayMode === 'grid'" class="file-grid">
					<view class="file-details" v-if="getCurrentTab().selectedFile">
						<view class="details-header">
							<text class="details-title">文件详情</text>
							<text class="details-close" @click="closeDetails">×</text>
						</view>
						<view class="details-content">
							<text class="detail-item"><strong>文件名:</strong> {{ getCurrentTab().selectedFile.name }}</text>
							<text class="detail-item"><strong>类型:</strong>
								{{ getExtensionFromMimeType(getCurrentTab().selectedFile.name) }}</text>
							<text class="detail-item"><strong>大小:</strong> {{ formatSize(getCurrentTab().selectedFile.size) }}</text>
							<text class="detail-item"><strong>修改日期:</strong> {{ getCurrentTab().selectedFile.modifiedDate }}</text>
							<text class="detail-item"><strong>位置:</strong> {{ getFullPath() }}</text>
						</view>
						<view class="details-actions">
							<button class="action-button">预览</button>
							<button class="action-button">下载</button>
							<button class="action-button">分享</button>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 管理员按钮 -->
		<!-- 		<view class="admin-button">
			<text class="admin-text">管理员</text>
		</view> -->

		<!-- 上传进度对话框 -->
		<view v-if="showUploadDialog" class="upload-dialog-overlay">
			<view class="upload-dialog" @click.stop>
				<view class="upload-dialog-header">
					<text class="upload-dialog-title">上传文件</text>
					<text class="upload-dialog-close" @click="cancelUpload" v-if="isUploading">×</text>
				</view>

				<view class="upload-dialog-content">
					<!-- 总体进度 -->
					<view class="overall-progress">
						<view class="progress-info">
							<text>总体进度: {{ totalProgress }}%</text>
							<text>上传速度: {{ uploadSpeed }}</text>
						</view>
						<view class="progress-bar">
							<view class="progress-fill" :style="{ width: totalProgress + '%' }"></view>
						</view>
						<view class="size-info">
							<text>{{ formatSize(uploadedSize) }} / {{ formatSize(totalSize) }}</text>
						</view>
					</view>

					<!-- 文件列表 -->
					<view class="file-progress-list">
						<view v-for="(file, index) in uploadFiles" :key="index" class="file-progress-item">
							<view class="file-info">
								<text class="file-icon">{{ getFileIcon(file.type) }}</text>
								<text class="file-name">{{ file.name }}</text>
								<text class="file-size-small">{{ formatSize(file.size) }}</text>
							</view>
							<view class="file-progress">
								<view class="progress-bar-small">
									<view class="progress-fill-small" :style="{ width: file.progress + '%' }"
										:class="{ 'progress-error': file.status === 'error', 'progress-success': file.status === 'success' }">
									</view>
								</view>
								<text class="progress-text">{{ file.progress }}%</text>
								<text class="status-icon" v-if="file.status === 'success'">{{ '✓' }}</text>
								<text class="status-icon error" v-if="file.status === 'error'">{{ '✗' }}</text>
							</view>
						</view>
					</view>
				</view>

				<view class="upload-dialog-footer">
					<button v-if="isUploading" class="cancel-button" @click="cancelUpload">取消上传</button>
					<button v-else class="close-button" @click="showUploadDialog = false">关闭</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app"
	const db = uniCloud.databaseForJQL()

	// 上传进度相关状态
	const showUploadDialog = ref(false);
	const uploadFiles = ref([]);
	const totalProgress = ref(0);
	const isUploading = ref(false);
	const uploadSpeed = ref('0 MB/s');
	const startTime = ref(0);
	const totalSize = ref(0);
	const uploadedSize = ref(0);

	// 缓存机制：存储已加载的文件夹内容
	const folderCache = ref(new Map());

	//更改上传名字，以防冲突
	function modifyName(originalName = '', id) {
		const ext = originalName.match(/(\.\w+)$/)?.[1] || ''; // 保留后缀
		return id + ext;
	}
	onLoad(async () => {
		// console.log();
		document.title = '指绣云章数据库';
		// 只在页面加载时初始化文件系统，不立即加载所有数据
		fileSystem.value = {
			folders: [],
			rootFiles: [],
			// 按需加载文件夹内容
			async loadFolderContent(folderId = '') {
				// 检查缓存中是否已存在
				if (folderCache.value.has(folderId)) {
					return folderCache.value.get(folderId);
				}

				try {
					// 显示加载提示
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					let foldersResult;
					// 1. 查询该文件夹下的所有子文件夹
					const subfoldersQuery = db.collection('folders');
					if (folderId === '') {
						// 根目录：parentId不存在的文件夹
						foldersResult = await subfoldersQuery
							.where(`parentId==""||parentId==null`)
							.field(`_id,timestampToDate(updatedAt) as time,name,path`)
							.orderBy("name asc")
							.get();
						console.log(foldersResult);

					} else {
						// 非根目录：parentId等于当前文件夹ID
						foldersResult = await subfoldersQuery.where(`parentId=="${folderId}"`)
							.field(`_id,timestampToDate(updatedAt) as time,name,path`)
							.orderBy("name asc")
							.get();

					}
					let filesResult;
					// 2. 查询该文件夹下的所有文件
					const filesQuery = db.collection('files');
					if (folderId === '') {
						// 根目录：folderId为0或不存在的文件
						filesResult = await filesQuery.where(`folderId==""||folderId==null`)
							.field(`_id,timestampToDate(updatedAt) as time,name,type,size,cloudPath,folderId`)
							.orderBy("name asc")
							.get();
					} else {
						// 非根目录：folderId等于当前文件夹ID
						filesResult = await filesQuery.where(`folderId=="${folderId}"`)
							.field(`_id,timestampToDate(updatedAt) as time,name,type,size,cloudPath,folderId`)
							.orderBy("name asc")
							.get();
					}

					// 处理文件夹数据
					const folders = foldersResult.data.map(folder => ({
						id: folder._id,
						name: folder.name,
						path: folder.path,
						parentId: folder.parentId || '',
						updatedAt: folder.time,
						isExpanded: false,
						children: [], // 初始为空，需要时再加载
						isExpanded: false
					}));

					// 处理文件数据
					const files = filesResult.data.map(file => {
						// 尝试从ID中提取时间信息（如果ID包含时间戳部分）
						let timestamp = file.time;
						if (!timestamp && file._id && typeof file._id === 'string') {
							// 检查ID是否包含数字部分，这可能是时间戳
							const numericPart = file._id.match(/\d+/);
							if (numericPart) {
								timestamp = Number(numericPart[0]);
							}
						}

						// 如果还是没有时间戳，使用一个固定的默认时间（而不是当前时间）
						if (!timestamp) {
							timestamp = 0; // 使用Unix纪元时间作为默认值
						}

						return {
							id: file._id,
							name: file.name,
							type: file.type,
							size: file.size,
							modifiedDate: formatDate(timestamp),
							updatedAt: timestamp,
							url: file.cloudPath,
							folderId: file.folderId || ''
						};
					});

					// 创建返回结果
					const result = {
						folders,
						files
					};

					// 存入缓存
					folderCache.value.set(folderId, result);

					// 如果是根目录，更新全局文件夹列表
					if (folderId === '') {
						fileSystem.value.folders = folders;
						fileSystem.value.rootFiles = files;
					}

					return result;
				} catch (error) {
					console.error('加载文件夹内容失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
					return {
						folders: [],
						files: []
					};
				} finally {
					// 隐藏加载提示
					uni.hideLoading();
				}
			},
			// 清除文件夹缓存
			clearFolderCache(folderId) {
				if (folderId) {
					folderCache.value.delete(folderId);
				} else {
					folderCache.value.clear();
				}
			},
			// 根据路径获取文件夹内容的方法
			getFolderContent: function(path) {
				// 根目录情况
				if (!path || path.length === 0) {
					return {
						folders: this.folders.map(folder => ({
							id: folder.id,
							name: folder.name,
							path: folder.path,
							isExpanded: false,
							parentId: folder.parentId, // 包含 parentId 属性
							updatedAt: folder.updatedAt // 包含 updatedAt 属性
						})),
						files: this.rootFiles
					};
				}

				// 单级目录情况
				if (path.length === 1) {
					const folderName = path[0];
					const folder = this.folders.find(f => f.name === folderName);
					if (folder) {
						// 返回文件夹内容
						const subfolders = folder.children ? folder.children.map(child => ({
							id: child.id,
							name: child.name,
							path: child.path,
							isExpanded: false,
							parentId: child.parentId, // 包含 parentId 属性
							updatedAt: child.updatedAt // 包含 updatedAt 属性
						})) : [];
						return {
							folders: subfolders,
							files: folder.files || []
						};
					}
					// 默认返回空内容
					return {
						folders: [],
						files: []
					};
				}

				// 多级目录情况
				if (path.length >= 2) {
					let currentFolder = this.folders.find(f => f.name === path[0]);
					if (currentFolder) {
						// 遍历路径的后续部分
						for (let i = 1; i < path.length; i++) {
							if (currentFolder.children) {
								currentFolder = currentFolder.children.find(f => f.name === path[i]);
								if (!currentFolder) break;
							}
						}

						// 如果找到了最终文件夹
						if (currentFolder) {
							const subfolders = currentFolder.children ? currentFolder.children.map(child => ({
								id: child.id,
								name: child.name,
								path: child.path,
								isExpanded: false,
								parentId: child.parentId, // 包含 parentId 属性
								updatedAt: child.updatedAt // 包含 updatedAt 属性
							})) : [];
							return {
								folders: subfolders,
								files: currentFolder.files ? currentFolder.files.map(file => {
									// 统一的时间戳处理逻辑
									let timestamp = file.updatedAt || file.time;
									if (!timestamp && file.id && typeof file.id === 'string') {
										const numericPart = file.id.match(/\d+/);
										if (numericPart) {
											timestamp = Number(numericPart[0]);
										}
									}
									if (!timestamp) {
										timestamp = 0; // 使用Unix纪元时间作为默认值
									}

									return {
										...file,
										updatedAt: timestamp,
										time: timestamp
									};
								}) : []
							};
						}
					}

					// 默认返回空内容
					return {
						folders: [],
						files: []
					};
				}
			},
			// 根据ID查找文件夹的方法
			findFolderById: function(id) {
				function searchInFolders(foldersList) {
					for (const folder of foldersList) {
						if (folder.id === id) {
							return folder;
						}
						if (folder.children) {
							const found = searchInFolders(folder.children);
							if (found) {
								return found;
							}
						}
					}
					return null;
				}
				return searchInFolders(this.folders);
			},
			// 根据ID获取文件夹路径的方法
			getPathById: function(id) {
				const path = [];
				let found = false;

				function searchInFolders(foldersList) {
					for (const folder of foldersList) {
						path.push(folder.name);
						if (folder.id === id) {
							found = true;
							return true;
						}
						if (folder.children) {
							if (searchInFolders(folder.children)) {
								return true;
							}
						}
						path.pop();
					}
					return false;
				}

				searchInFolders(this.folders);
				return found ? path : [];
			},
			// 在指定路径下创建新文件夹的方法
			createFolder: function(name, parentPath) {
				// 找到父文件夹
				let parentFolder;

				if (!parentPath || parentPath.length === 0) {
					// 根目录
					const newFolder = {
						id: '', // 暂时为空，数据库会生成
						name: name,
						path: `/${name}`,
						isExpanded: false,
						children: [],
						files: []
					};
					this.folders.push(newFolder);
					return newFolder;
				} else if (parentPath.length === 1) {
					parentFolder = this.folders.find(f => f.name === parentPath[0]);
				} else {
					// 多级路径
					parentFolder = this.folders.find(f => f.name === parentPath[0]);
					if (parentFolder) {
						for (let i = 1; i < parentPath.length; i++) {
							if (parentFolder.children) {
								parentFolder = parentFolder.children.find(f => f.name === parentPath[i]);
								if (!parentFolder) break;
							}
						}
					}
				}

				// 如果找到了父文件夹，创建新文件夹
				if (parentFolder) {
					if (!parentFolder.children) {
						parentFolder.children = [];
					}

					const folderPath = `/${parentPath.join('/')}/${name}`;

					const newFolder = {
						id: '', // 暂时为空，数据库会生成
						name: name,
						path: folderPath,
						isExpanded: false,
						children: [],
						files: []
					};

					parentFolder.children.push(newFolder);
					return newFolder;
				}

				return null;
			}
		};

		// 首次加载时，只加载根目录内容
		try {
			await fileSystem.value.loadFolderContent('');
			// 强制更新当前标签页的文件夹内容，确保中间区域能正确渲染
			nextTick(() => {
				const currentTab = getCurrentTab();
				currentTab.currentFolder = getInitialFolder();
				// 触发视图更新
				tabs.value = [...tabs.value];
			});
		} catch (error) {
			console.error('初始化文件系统失败:', error);
		}
	});

	// 引入nextTick用于确保DOM更新完成后执行操作
	import {
		nextTick
	} from 'vue';
	// const currentFolderName = getCurrentTab().title;

	// 下载文件
	function downloadFile(file) {
		if (file && file.url) {
			// 创建临时链接并触发下载
			const link = document.createElement('a');
			link.href = file.url;
			link.download = file.name;
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
		} else {
			uni.showToast({
				title: '文件链接不存在',
				icon: 'none'
			});
		}
	}

	// 兼容旧的下载方法
	function download() {
		const currentTab = getCurrentTab();
		if (currentTab.selectedFile && currentTab.selectedFile.type !== 'folder') {
			downloadFile(currentTab.selectedFile);
		}
	}



	// 更新上传进度的函数
	function updateProgress(fileIndex, loaded, total) {
		const file = uploadFiles.value[fileIndex];
		if (file) {
			// 确保loaded不大于total
			const safeLoaded = Math.min(loaded, total);
			file.loaded = safeLoaded;
			// 确保进度不超过100%
			file.progress = Math.min(Math.round((safeLoaded * 100) / total), 100);

			// 计算已上传的总大小
			let currentUploadedSize = 0;
			uploadFiles.value.forEach(f => {
				currentUploadedSize += f.loaded;
			});
			uploadedSize.value = currentUploadedSize;

			// 计算总体进度，确保不超过100%
			totalProgress.value = Math.min(Math.round((currentUploadedSize * 100) / totalSize.value), 100);

			// 计算上传速度
			if (startTime.value > 0) {
				const elapsed = (Date.now() - startTime.value) / 1000; // 秒
				const speed = currentUploadedSize / elapsed; // 字节/秒
				if (speed > 1024 * 1024) {
					uploadSpeed.value = (speed / (1024 * 1024)).toFixed(2) + ' MB/s';
				} else if (speed > 1024) {
					uploadSpeed.value = (speed / 1024).toFixed(2) + ' KB/s';
				} else {
					uploadSpeed.value = speed.toFixed(2) + ' B/s';
				}
			}
		}
	}

	// 取消上传
	function cancelUpload() {
		isUploading.value = false;
		showUploadDialog.value = false;
		uploadFiles.value = [];
		totalProgress.value = 0;
		uploadSpeed.value = '0 MB/s';
	}

	function upload() {
		uni.chooseFile({
			count: 100, // 最大选择数量
			type: 'all',
			success: (res) => {
				if (res.tempFilePaths.length > 0) {
					// 重置上传状态
					isUploading.value = true;
					startTime.value = Date.now();
					totalSize.value = 0;
					uploadedSize.value = 0;
					totalProgress.value = 0;
					uploadSpeed.value = '0 MB/s';

					// 初始化上传文件列表
					uploadFiles.value = res.tempFiles.map((file, index) => {
						totalSize.value += file.size;
						return {
							name: file.name,
							type: file.type,
							size: file.size,
							progress: 0,
							loaded: 0,
							status: 'waiting', // waiting, uploading, success, error
							filePath: res.tempFilePaths[index]
						};
					});

					// 显示上传进度对话框
					showUploadDialog.value = true;

					// 开始上传文件
					uploadFilesSequentially(res);
				}
			}
		})
	}

	// 顺序上传文件
	async function uploadFilesSequentially(res) {
		// 获取当前所在文件夹的ID
		const currentTab = getCurrentTab();
		const currentFolderId = currentTab.currentFolder && currentTab.currentFolder.id ? currentTab
			.currentFolder.id : "";

		// 遍历所有选择的文件
		for (let i = 0; i < res.tempFilePaths.length; i++) {
			if (!isUploading.value) break; // 如果用户取消上传，则停止

			const fileIndex = i;
			const file = uploadFiles.value[fileIndex];
			file.status = 'uploading';

			try {
				// 获取当前日期并格式化年月
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const monthFolder = `${year}-${month}`;

				let filePath = res.tempFilePaths[i];
				let fileName = res.tempFiles[i].name;

				// 先在数据库中创建文件记录，包含时间戳
				const currentTime = new Date().getTime();
				const temp = await db.collection("files").add({
					name: fileName,
					type: res.tempFiles[i].type,
					size: res.tempFiles[i].size,
					userId: uniCloud.getCurrentUserInfo().uid,
					folderId: currentFolderId,
					createdAt: currentTime,
					updatedAt: currentTime
				})

				const cloudPath = `files/${monthFolder}/${modifyName(fileName, temp.id)}`;

				// 上传文件到云存储
				const result = await uniCloud.uploadFile({
					filePath: filePath,
					cloudPathAsRealPath: true,
					cloudPath: cloudPath,
					onUploadProgress: (progressEvent) => {
						updateProgress(fileIndex, progressEvent.loaded, progressEvent.total);
					}
				});

				// 更新数据库中的文件记录，添加cloudPath
				await db.collection("files")
					.doc(temp.id)
					.update({
						cloudPath: result.fileID
					})

				// 更新文件状态为成功
				file.status = 'success';
				file.progress = 100;
				file.loaded = file.size;

				// 清除当前文件夹的缓存
				fileSystem.value.clearFolderCache(currentFolderId);

				// 重新加载当前文件夹内容
				const updatedContent = await fileSystem.value.loadFolderContent(currentFolderId);

				// 更新当前标签页的文件夹内容
				currentTab.currentFolder = {
					id: currentFolderId,
					...updatedContent
				};

				// 强制更新以确保视图正确显示
				tabs.value = [...tabs.value];
			} catch (error) {
				console.error('文件上传失败:', error);
				file.status = 'error';
			}
		}

		// 所有文件上传完成
		if (isUploading.value) {
			isUploading.value = false;
			// 可以在这里添加上传完成的提示
		}
	}
	// 移动文件到回收站
	async function deleteFolder(folder) {
		try {
			// 显示确认对话框
			const modalResult = await new Promise((resolve, reject) => {
				uni.showModal({
					title: "正在执行危险操作",
					content: `您正在删除文件夹【${folder.name}】，此操作不可恢复！`,
					success: resolve,
					fail: reject
				})
			});

			if (modalResult.confirm) {
				// 显示加载提示
				uni.showLoading({
					title: '删除中...',
					mask: true
				});

				const currentTab = getCurrentTab();
				const parentFolderId = currentTab.currentFolder.id || '';

				await db.collection("folders").doc(folder.id).update({
					parentId: '0'
				})

				// 同步到数据库
				// await db.collection('folders').doc(folder.id).remove();

				// 删除与该文件夹相关的文件
				// const fileRes = await db.collection('files').where({
				// 	folderId: folder.id,
				// 	userId: uniCloud.getCurrentUserInfo().uid
				// }).get();

				// if (fileRes.data.length > 0) {
				// 	// 批量删除文件
				// 	const deleteTasks = fileRes.data.map(file => {
				// 		// 删除云存储中的文件
				// 		if (file.cloudPath) {
				// 			return uniCloud.deleteFile({
				// 				fileList: [file.cloudPath]
				// 			}).catch(() => {
				// 				/* 忽略文件删除错误 */
				// 			});
				// 		}
				// 		return Promise.resolve();
				// 	});

				// 	await Promise.all(deleteTasks);

				// 	// 删除数据库中的文件记录
				// 	await db.collection('files').where({
				// 		folderId: folder.id,
				// 		userId: uniCloud.getCurrentUserInfo().uid
				// 	}).remove();
				// }

				// 清除当前文件夹和被删除文件夹的缓存
				fileSystem.value.clearFolderCache(parentFolderId);
				fileSystem.value.clearFolderCache(folder.id);

				// 重新加载当前文件夹内容
				const updatedContent = await fileSystem.value.loadFolderContent(parentFolderId);

				// 更新当前标签页的文件夹内容
				currentTab.currentFolder = {
					id: parentFolderId,
					...updatedContent
				};

				// 如果是根目录，还需要更新fileSystem
				if (parentFolderId === '') {
					fileSystem.value.folders = updatedContent.folders;
				}

				// 强制更新以确保视图正确显示
				tabs.value = [...tabs.value];

				uni.showToast({
					title: '删除成功',
					icon: 'success'
				});
			}
		} catch (error) {
			console.error('删除文件夹失败:', error);
			uni.showToast({
				title: '删除失败',
				icon: 'none'
			});
		} finally {
			// 隐藏加载提示
			uni.hideLoading();
		}
	}
	// 移动文件夹到回收站
	async function deleteFile(file) {
		try {
			// 显示确认对话框
			const modalResult = await new Promise((resolve, reject) => {
				uni.showModal({
					title: "正在执行危险操作",
					content: `您正在删除文件【${file.name}】，此操作不可恢复！`,
					success: resolve,
					fail: reject
				})
			});

			if (modalResult.confirm) {
				// 显示加载提示
				uni.showLoading({
					title: '删除中...',
					mask: true
				});

				const currentTab = getCurrentTab();
				const parentFolderId = currentTab.currentFolder.id || '';

				// 同步到数据库
				// await db.collection('files').doc(file.id).remove();
				await db.collection('files').doc(file.id).update({
					folderId: '0'
				});

				// 删除云存储中的文件
				// if (file.cloudPath) {
				// 	try {
				// 		await uniCloud.deleteFile({
				// 			fileList: [file.cloudPath]
				// 		});
				// 	} catch (cloudError) {
				// 		console.warn('云存储文件删除失败，但继续执行数据库操作:', cloudError);
				// 	}
				// }

				// 清除当前文件夹的缓存
				fileSystem.value.clearFolderCache(parentFolderId);

				// 重新加载当前文件夹内容
				const updatedContent = await fileSystem.value.loadFolderContent(parentFolderId);

				// 更新当前标签页的文件夹内容
				currentTab.currentFolder = {
					id: parentFolderId,
					...updatedContent
				};

				// 强制更新以确保视图正确显示
				tabs.value = [...tabs.value];

				uni.showToast({
					title: '删除成功',
					icon: 'success'
				});
			}
		} catch (error) {
			console.error('删除文件失败:', error);
			uni.showToast({
				title: '删除失败',
				icon: 'none'
			});
		} finally {
			// 隐藏加载提示
			uni.hideLoading();
		}
	}

	function renameFolder(folder) {
		console.log(folder);
	}

	// 统一的文件系统数据管理
	const fileSystem = ref({

		folders: [],
		rootFiles: [],
		// 根据路径获取文件夹内容的方法
		getFolderContent: function(path) {
			// 根目录情况
			if (!path || path.length === 0) {
				return {
					folders: this.folders.map(folder => ({
						id: folder.id,
						name: folder.name,
						path: folder.path,
						isExpanded: false,
						parentId: folder.parentId, // 包含 parentId 属性
						updatedAt: folder.updatedAt // 包含 updatedAt 属性
					})),
					files: this.rootFiles.map(file => {
						// 统一的时间戳处理逻辑
						let timestamp = file.updatedAt || file.time;
						if (!timestamp && file.id && typeof file.id === 'string') {
							const numericPart = file.id.match(/\d+/);
							if (numericPart) {
								timestamp = Number(numericPart[0]);
							}
						}
						if (!timestamp) {
							timestamp = 0; // 使用Unix纪元时间作为默认值
						}

						return {
							...file,
							updatedAt: timestamp,
							time: timestamp
						};
					})
				};
			}

			// 单级目录情况
			if (path.length === 1) {
				const folderName = path[0];
				const folder = this.folders.find(f => f.name === folderName);
				if (folder) {
					// 返回文件夹内容
					const subfolders = folder.children ? folder.children.map(child => ({
						id: child.id,
						name: child.name,
						path: child.path,
						isExpanded: false,
						parentId: child.parentId, // 包含 parentId 属性
						updatedAt: child.updatedAt // 包含 updatedAt 属性
					})) : [];
					return {
						folders: subfolders,
						files: folder.files ? folder.files.map(file => {
							// 统一的时间戳处理逻辑
							let timestamp = file.updatedAt || file.time;
							if (!timestamp && file.id && typeof file.id === 'string') {
								const numericPart = file.id.match(/\d+/);
								if (numericPart) {
									timestamp = Number(numericPart[0]);
								}
							}
							if (!timestamp) {
								timestamp = 0; // 使用Unix纪元时间作为默认值
							}

							return {
								...file,
								updatedAt: timestamp,
								time: timestamp
							};
						}) : []
					};
				}
				// 默认返回空内容
				return {
					folders: [],
					files: []
				};
			}

			// 多级目录情况
			if (path.length >= 2) {
				let currentFolder = this.folders.find(f => f.name === path[0]);
				if (currentFolder) {
					// 遍历路径的后续部分
					for (let i = 1; i < path.length; i++) {
						if (currentFolder.children) {
							currentFolder = currentFolder.children.find(f => f.name === path[i]);
							if (!currentFolder) break;
						}
					}

					// 如果找到了最终文件夹
					if (currentFolder) {
						const subfolders = currentFolder.children ? currentFolder.children.map(child => ({
							id: child.id,
							name: child.name,
							path: child.path,
							isExpanded: false,
							parentId: child.parentId, // 包含 parentId 属性
							updatedAt: child.updatedAt // 包含 updatedAt 属性
						})) : [];
						return {
							folders: subfolders,
							files: currentFolder.files || []
						};
					}
				}

				// 默认返回空内容
				return {
					folders: [],
					files: []
				};
			}
		},

		// 根据ID查找文件夹的方法
		findFolderById: function(id) {
			function searchInFolders(foldersList) {
				for (const folder of foldersList) {
					if (folder.id === id) {
						return folder;
					}
					if (folder.children) {
						const found = searchInFolders(folder.children);
						if (found) {
							return found;
						}
					}
				}
				return null;
			}
			return searchInFolders(this.folders);
		},
		// 根据ID获取文件夹路径的方法
		getPathById: function(id) {
			const path = [];
			let found = false;

			function searchInFolders(foldersList) {
				for (const folder of foldersList) {
					path.push(folder.name);
					if (folder.id === id) {
						found = true;
						return true;
					}
					if (folder.children) {
						if (searchInFolders(folder.children)) {
							return true;
						}
					}
					path.pop();
				}
				return false;
			}

			searchInFolders(this.folders);
			return found ? path : [];
		},
		// 在指定路径下创建新文件夹的方法
		createFolder: function(name, parentPath) {
			// 找到父文件夹
			let parentFolder;

			if (!parentPath || parentPath.length === 0) {
				// 根目录
				const maxId = this.folders.length > 0 ? Math.max(...this.folders.map(f => f.id)) : 0;
				const newFolder = {
					id: uniCloud.getCurrentUserInfo().uid + Date.now(),
					name: name,
					path: `/${name}`,
					isExpanded: false,
					children: [],
					files: []
				};
				this.folders.push(newFolder);
				return newFolder;
			} else if (parentPath.length === 1) {
				parentFolder = this.folders.find(f => f.name === parentPath[0]);
			} else {
				// 多级路径
				parentFolder = this.folders.find(f => f.name === parentPath[0]);
				if (parentFolder) {
					for (let i = 1; i < parentPath.length; i++) {
						if (parentFolder.children) {
							parentFolder = parentFolder.children.find(f => f.name === parentPath[i]);
							if (!parentFolder) break;
						}
					}
				}
			}

			// 如果找到了父文件夹，创建新文件夹
			if (parentFolder) {
				if (!parentFolder.children) {
					parentFolder.children = [];
				}

				const maxId = parentFolder.children.length > 0 ?
					Math.max(...parentFolder.children.map(f => f.id)) : 0;
				const folderPath = `/${parentPath.join('/')}/${name}`;

				const newFolder = {
					id: uniCloud.getCurrentUserInfo().uid + Date.now(),
					name: name,
					path: folderPath,
					isExpanded: false,
					children: [],
					files: []
				};

				parentFolder.children.push(newFolder);
				return newFolder;
			}

			return null;
		}
	});

	// 获取初始文件夹结构（从统一数据源获取）
	const getInitialFolder = () => ({
		id: "",
		folders: fileSystem.value.folders.map(folder => ({
			id: folder.id,
			name: folder.name,
			path: folder.path,
			isExpanded: false,
			parentId: folder.parentId, // 包含 parentId 属性
			updatedAt: folder.updatedAt // 包含 updatedAt 属性
		})),
		files: fileSystem.value.rootFiles.map(file => ({
			...file,
			updatedAt: file.updatedAt || file.time // 确保包含 updatedAt 属性
		}))
	});

	// 标签页数据 - 每个标签页有独立的状态
	const tabs = ref(
		[{
				id: 0,
				title: "首页",
				currentPath: [],
				currentFolder: getInitialFolder(),
				selectedFile: null,
				displayMode: 'list'
			}

		]
	);
	const activeTab = ref(0);

	// 搜索查询
	const searchQuery = ref("");

	// 文件目录结构 - 直接使用统一数据源
	const folders = computed(() => fileSystem.value.folders);

	// 新建文件夹相关
	const showRenameDialog = ref(false);
	const newFolderName = ref('');

	// 双击事件相关变量
	const clickTimer = ref(null);
	const isDoubleClick = ref(false);

	// 获取当前激活标签的状态
	const getCurrentTab = () => tabs.value[activeTab.value];

	// 添加新标签页
	function addTab() {
		const newId = Math.max(...tabs.value.map(t => t.id)) + 1;
		tabs.value.push({
			id: newId,
			title: "首页",
			currentPath: [],
			currentFolder: getInitialFolder(),
			selectedFile: null,
			displayMode: 'list'
		});
		activeTab.value = tabs.value.length - 1;
		// 确保新标签页的文件夹状态与左侧同步
		syncFolderExpansionState(fileSystem.value.folders, tabs.value[activeTab.value].currentPath);
	}

	// 关闭标签页
	function closeTab(index) {
		// 确保至少保留一个标签页
		if (tabs.value.length <= 1) return;
		tabs.value.splice(index, 1);
		if (activeTab.value >= index) {
			activeTab.value = Math.min(activeTab.value, tabs.value.length - 1);
		}
	}

	// 切换标签页
	function switchTab(index) {
		activeTab.value = index;
		// 切换标签页后，同步左侧文件夹的展开状态
		const currentTab = getCurrentTab();
		syncFolderExpansionState(fileSystem.value.folders, currentTab.currentPath);
	}

	// 同步文件夹展开状态
	function syncFolderExpansionState(foldersList, path) {
		if (!path || path.length === 0) return;

		// 重置所有文件夹的展开状态
		function resetExpansion(folders) {
			folders.forEach(folder => {
				folder.isExpanded = false;
				if (folder.children) {
					resetExpansion(folder.children);
				}
			});
		}
		resetExpansion(foldersList);

		// 根据路径展开对应文件夹
		function expandPath(folders, remainingPath) {
			if (!remainingPath || remainingPath.length === 0) return;

			const folderName = remainingPath[0];
			const folder = folders.find(f => f.name === folderName);

			if (folder) {
				folder.isExpanded = true;
				if (folder.children && remainingPath.length > 1) {
					expandPath(folder.children, remainingPath.slice(1));
				}
			}
		}
		expandPath(foldersList, path);
	}

	// 展开/折叠文件夹
	function toggleFolder(folder) {
		if (folder.children && folder.children.length > 0) {
			folder.isExpanded = !folder.isExpanded;
			// 如果是展开操作，则同时加载该文件夹内容
			if (folder.isExpanded) {
				const currentTab = getCurrentTab();
				currentTab.currentPath = [folder.name];
				currentTab.title = folder.name;
				// 根据文件夹ID加载不同内容
				openFolderById(folder.id);
			}
		}
	}

	// 通过ID打开文件夹
	async function openFolderById(id) {
		try {
			// 显示加载提示
			uni.showLoading({
				title: '加载中...',
				mask: true
			});

			// 按需加载文件夹内容
			const folderContent = await fileSystem.value.loadFolderContent(id);

			const folder = fileSystem.value.findFolderById(id);
			if (folder) {
				// 更新文件夹的子文件夹和文件
				folder.children = folderContent.folders;
				folder.files = folderContent.files;

				const currentTab = getCurrentTab();
				// 从统一数据源获取路径
				currentTab.currentPath = fileSystem.value.getPathById(id);
				// 更新标签标题为当前文件夹名称
				currentTab.title = folder.name;
				// 同步更新左侧文件夹的展开状态
				syncFolderExpansionState(fileSystem.value.folders, currentTab.currentPath);
				// 设置当前文件夹内容
				currentTab.currentFolder = {
					id: folder.id,
					...folderContent
				};
				// 触发视图更新
				tabs.value = [...tabs.value];
			}
		} catch (error) {
			console.error('打开文件夹失败:', error);
			uni.showToast({
				title: '打开文件夹失败',
				icon: 'none'
			});
		} finally {
			// 隐藏加载提示
			uni.hideLoading();
		}
	}

	// 兼容旧的打开文件夹方法
	function openFolder(index) {
		const folder = folders.value[index];
		openFolderById(folder.id);
	}

	// 打开子文件夹
	async function openSubFolder(folder) {
		try {
			// 显示加载提示
			uni.showLoading({
				title: '加载中...',
				mask: true
			});

			// 按需加载文件夹内容
			const folderContent = await fileSystem.value.loadFolderContent(folder.id);

			// 更新文件夹的子文件夹和文件
			folder.children = folderContent.folders;
			folder.files = folderContent.files;

			const currentTab = getCurrentTab();
			currentTab.currentPath.push(folder.name);
			// 更新标签标题为当前文件夹名称
			currentTab.title = folder.name;
			// 同步更新左侧文件夹的展开状态
			syncFolderExpansionState(fileSystem.value.folders, currentTab.currentPath);

			// 设置当前文件夹内容
			currentTab.currentFolder = {
				id: folder.id,
				...folderContent
			};
			// 触发视图更新
			tabs.value = [...tabs.value];
		} catch (error) {
			console.error('打开子文件夹失败:', error);
			uni.showToast({
				title: '打开文件夹失败',
				icon: 'none'
			});
		} finally {
			// 隐藏加载提示
			uni.hideLoading();
		}
	}

	// 导航到根目录
	function navigateToRoot() {
		const currentTab = getCurrentTab();
		currentTab.currentPath = [];
		// 重置到初始页面内容
		currentTab.currentFolder = getInitialFolder();
		// 清空选中的文件
		currentTab.selectedFile = null;
		// 更新标签标题为首页
		currentTab.title = "首页";
		// 同步更新左侧文件夹的展开状态
		syncFolderExpansionState(fileSystem.value.folders, currentTab.currentPath);
	}

	// 导航到指定路径
	async function navigateToPath(index) {
		try {
			// 显示加载提示
			uni.showLoading({
				title: '加载中...',
				mask: true
			});

			const currentTab = getCurrentTab();
			// 更新路径
			currentTab.currentPath = currentTab.currentPath.slice(0, index + 1);
			// 同步更新左侧文件夹的展开状态
			syncFolderExpansionState(fileSystem.value.folders, currentTab.currentPath);

			// 获取当前路径对应的文件夹ID
			let folderId = '';
			if (currentTab.currentPath.length > 0) {
				// 查找当前路径对应的文件夹，以获取ID
				let currentFolder = fileSystem.value.folders.find(f => f.name === currentTab.currentPath[0]);
				if (currentFolder) {
					for (let i = 1; i < currentTab.currentPath.length; i++) {
						if (currentFolder.children) {
							currentFolder = currentFolder.children.find(f => f.name === currentTab.currentPath[i]);
							if (!currentFolder) break;
						}
					}
					if (currentFolder) {
						folderId = currentFolder.id;
					}
				}
			}

			// 按需加载文件夹内容
			const folderContent = await fileSystem.value.loadFolderContent(folderId);

			// 设置当前文件夹内容
			currentTab.currentFolder = {
				id: folderId,
				...folderContent
			};

			// 更新标签标题
			currentTab.title = currentTab.currentPath.length > 0 ?
				currentTab.currentPath[currentTab.currentPath.length - 1] : "首页";

			// 清空选中的文件
			currentTab.selectedFile = null;

			// 触发视图更新
			tabs.value = [...tabs.value];
		} catch (error) {
			console.error('导航到路径失败:', error);
			uni.showToast({
				title: '加载文件夹失败',
				icon: 'none'
			});
		} finally {
			// 隐藏加载提示
			uni.hideLoading();
		}
	}

	// 获取文件图标
	function getFileIcon(type) {
		const iconMap = {
			"文档": "📄",
			"图片": "🖼️",
			"演示文稿": "📊",
			"表格": "📈",
			"PDF": "📋",
			"压缩文件": "🗜️",
			"视频": "🎬",
			"音频": "🎵"
		};
		return iconMap[type] || "📄";
	}

	// 将MIME类型映射为友好的文件扩展名
	function getExtensionFromMimeType(mimeType) {
		/*
		const mimeMap = {
		  'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
		  'application/msword': 'doc',
		  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
		  'application/vnd.ms-excel': 'xls',
		  'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
		  'application/vnd.ms-powerpoint': 'ppt',
		  'application/pdf': 'pdf',
		  'image/jpeg': 'jpg',
		  'image/png': 'png',
		  'image/gif': 'gif',
		  'video/mp4': 'mp4',
		  'audio/mpeg': 'mp3',
		  'text/plain': 'txt',
		  'application/zip': 'zip',
		  'application/x-rar-compressed': 'rar'
		};
		return mimeMap[mimeType] || mimeType;
		*/
		return mimeType.match(/(\.\w+)$/)?.[1] || '';
	}

	// 格式化文件大小
	function formatSize(bytes) {
		if (bytes === 0) return "0 B";
		const k = 1024;
		const sizes = ["B", "KB", "MB", "GB", "TB"];
		const i = Math.floor(Math.log(bytes) / Math.log(k));
		return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
	}

	// 格式化日期时间
	function formatDate(dateString) {
		if (!dateString) return '';
		const date = new Date(dateString);
		// 检查是否是有效日期
		if (isNaN(date.getTime())) return '';
		// 格式化日期为 YYYY-MM-DD HH:MM 格式
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	}

	// 获取完整路径
	function getFullPath() {
		const currentTab = getCurrentTab();
		return "/" + currentTab.currentPath.join("/");
	}

	// 切换显示模式(网格视图/列表视图)
	function toggleDisplayMode() {
		const currentTab = getCurrentTab();
		currentTab.displayMode = currentTab.displayMode === 'grid' ? 'list' : 'grid';
	}

	// 关闭文件详情
	function closeDetails() {
		const currentTab = getCurrentTab();
		currentTab.selectedFile = null;
	}

	// 新建文件夹
	function createNewFolder() {
		newFolderName.value = '新建文件夹';
		showRenameDialog.value = true;
		// 延迟聚焦到输入框，确保DOM已经渲染
		setTimeout(() => {
			const input = document.querySelector('.dialog-input');
			if (input) {
				input.focus();
				// input.select();
			}
		}, 100);
	}

	// 确认重命名
	async function confirmRename() {
		if (newFolderName.value.trim()) {
			const currentTab = getCurrentTab();
			const currentFolderId = currentTab.currentFolder.id || '';
			const folderName = newFolderName.value.trim();

			// 检查当前文件夹是否已存在同名文件夹
			const hasSameNameFolder = currentTab.currentFolder.folders.some(folder =>
				folder.name === folderName
			);

			if (hasSameNameFolder) {
				// 显示提示信息
				uni.showToast({
					title: '文件夹名称重复',
					icon: 'none'
				});
				return; // 不继续执行创建操作
			}

			try {
				// 直接在数据库中创建新文件夹
				const newFolder = {
					name: folderName,
					parentId: currentFolderId,
					path: '',
					userId: uniCloud.getCurrentUserInfo().uid,
					createdAt: new Date().getTime(),
					updatedAt: new Date().getTime()
				};

				// 调用云函数或直接操作数据库保存文件夹
				const result = await db.collection('folders').add(newFolder);
				console.log('文件夹已保存到数据库:', result);

				// 清除当前文件夹的缓存，以便下次访问时重新加载
				fileSystem.value.clearFolderCache(currentFolderId);

				// 重新加载当前文件夹内容，以获取最新数据
				const updatedContent = await fileSystem.value.loadFolderContent(currentFolderId);

				// 更新当前标签页的文件夹内容
				currentTab.currentFolder = {
					id: currentFolderId,
					...updatedContent
				};

				// 如果是根目录，还需要更新fileSystem
				if (currentFolderId === '') {
					fileSystem.value.folders = updatedContent.folders;
				}

				// 强制更新以确保视图正确显示
				tabs.value = [...tabs.value];

				uni.showToast({
					title: '文件夹创建成功',
					icon: 'success'
				});
			} catch (error) {
				console.error('创建文件夹失败:', error);
				uni.showToast({
					title: '创建文件夹失败',
					icon: 'none'
				});
			}

			// 关闭弹窗
			showRenameDialog.value = false;
			newFolderName.value = '';
		}
	}

	// 将文件夹同步到数据库
	async function syncFolderToDatabase(folder, parentId) {
		try {
			// 准备文件夹数据，按照数据库模式
			const folderData = {
				name: folder.name,
				parentId: parentId || '', // 根目录为''
				path: folder.path,
				isExpanded: false,
				userId: uniCloud.getCurrentUserInfo().uid,
				createdAt: new Date().getTime(),
				updatedAt: new Date().getTime()
			};

			// 调用云函数或直接操作数据库保存文件夹
			const result = await db.collection('folders').add(folderData);
			console.log('文件夹已保存到数据库:', result);

			// 更新前端数据中的ID为数据库生成的ID
			folder.id = result.id;
		} catch (error) {
			console.error('同步文件夹到数据库失败:', error);
			uni.showToast({
				title: '创建文件夹失败',
				icon: 'none'
			});
		}
	}

	// 取消重命名
	function cancelRename() {
		showRenameDialog.value = false;
		newFolderName.value = '';
	}

	// 在新标签页预览文件
	function previewFileInNewTab(file) {
		// 添加新标签页
		const newId = Math.max(...tabs.value.map(t => t.id)) + 1;
		tabs.value.push({
			id: newId,
			title: file.name,
			currentPath: getCurrentTab().currentPath,
			currentFolder: {
				...getCurrentTab().currentFolder
			},
			selectedFile: file,
			displayMode: getCurrentTab().displayMode
		});
		// 切换到新标签页
		activeTab.value = tabs.value.length - 1;
		// 可以在这里添加文件预览的逻辑
		console.log('预览文件:', file);
	}

	// 处理项目点击事件（防止双击时触发单击）
	function handleItemClick(item, type) {
		// 重置双击状态
		isDoubleClick.value = false;

		// 清除之前的定时器
		if (clickTimer.value) {
			clearTimeout(clickTimer.value);
		}

		// 设置新的定时器，延迟执行单击操作
		clickTimer.value = setTimeout(() => {
			// 只有在不是双击的情况下才执行单击操作
			if (!isDoubleClick.value) {
				const currentTab = getCurrentTab();
				// 存储选中的文件，以便在模板中应用选中样式
				currentTab.selectedFile = item;
			}
		}, 300); // 300毫秒是区分单击和双击的常用阈值
	}

	// 处理项目双击事件
	function handleItemDblClick(item, type) {
		// 设置双击状态为true
		isDoubleClick.value = true;

		// 清除定时器，防止单击操作执行
		if (clickTimer.value) {
			clearTimeout(clickTimer.value);
		}

		// 执行双击操作
		if (type === 'folder') {
			openSubFolder(item);
		} else {
			previewFileInNewTab(item);
		}
	}
</script>

<style scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f5f7fa;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
	}

	/* 标签页样式 */
	.tabs-container {
		display: flex;
		background-color: #fff;
		border-bottom: 1px solid #e5e5e5;
		padding: 0 10px;
		overflow-x: auto;
		scrollbar-width: none;
		/* Firefox */
		flex-wrap: nowrap;
	}

	/* 隐藏滚动条但保持滚动功能 */
	.tabs-container::-webkit-scrollbar {
		display: none;
		/* Chrome, Safari, Edge */
	}

	/* Logo样式 */
	.logo {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 10px;
		padding: 5px;
	}

	.logo-image {
		height: 40px;
		width: auto;
		border-radius: 4px;
	}

	.tab {
		flex: 0 1 200px;
		min-width: 50px;
		display: flex;
		align-items: center;
		padding: 10px 15px;
		margin-right: 5px;
		border-bottom: 3px solid transparent;
		cursor: pointer;
		background-color: #f5f5f5;
		border-radius: 10px
	}

	.tab.active {
		background-color: #459fc9;
	}

	.tab-icon {
		margin-right: 5px;
	}

	.tab-icon image {
		width: 20px;
		height: 20px;
	}

	.tab-title {
		margin-right: 10px;
	}

	.tab-close {
		color: #999;
		font-size: 16px;
		line-height: 1;
		margin-left: auto;
	}

	.tab-close:hover {
		color: #333;
	}

	.new-tab {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 30px;
		height: 30px;
		margin: 10px 5px;
		background-color: #f5f5f5;
		border-radius: 5px;
		cursor: pointer;
	}

	.new-tab:hover {
		background-color: #e5e5e5;
	}

	/* 工具栏样式 */
	.toolbar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 20px;
		background-color: #fff;
		border-bottom: 1px solid #e5e5e5;
	}

	.search-container {
		display: flex;
		align-items: center;
		background-color: #f5f5f5;
		border-radius: 20px;
		padding: 5px 15px;
		width: 400px;
	}

	.search-icon {
		margin-right: 10px;
		color: #999;
	}

	.search-input {
		flex: 1;
		border: none;
		background: transparent;
		outline: none;
		font-size: 14px;
	}

	.toolbar-buttons {
		display: flex;
		gap: 10px;
	}

	.toolbar-button {
		padding: 8px 16px;
		background-color: #1989fa;
		color: white;
		border: none;
		border-radius: 5px;
		cursor: pointer;
		font-size: 14px;
	}

	.toolbar-button:hover {
		opacity: 0.8;
	}

	/* 主内容区样式 */
	.main-content {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	/* 侧边栏样式 */
	.sidebar {
		width: 200px;
		background-color: #fff;
		border-right: 1px solid #e5e5e5;
		overflow-y: auto;
	}

	.folder-item-wrapper {
		width: 100%;
	}

	.folder-item {
		display: flex;
		align-items: center;
		padding: 8px 15px;
		cursor: pointer;
		transition: background-color 0.2s;
	}

	.folder-item:hover {
		background-color: #f5f5f5;
	}

	.folder-icon {
		margin-right: 8px;
		font-size: 16px;
	}

	.folder-name {
		font-size: 14px;
		flex: 1;
	}

	/* 展开/折叠图标样式 */
	.expand-icon {
		width: 16px;
		text-align: center;
		font-size: 10px;
		margin-right: 4px;
		color: #666;
		transition: transform 0.2s;
	}

	/* 缩进样式 */
	.indent {
		width: 16px;
		display: inline-block;
	}

	/* 子文件夹样式 */
	.subfolders {
		margin-left: 20px;
		background-color: #f9f9f9;
		border-left: 1px solid #e0e0e0;
	}

	/* 文件展示区域样式 */
	.file-display {
		flex: 1;
		padding: 20px;
		overflow-y: auto;
		position: relative;
	}

	/* 面包屑导航样式 */
	.breadcrumb {
		margin-bottom: 20px;
		font-size: 14px;
		color: #666;
	}

	.breadcrumb-item {
		color: #1989fa;
		cursor: pointer;
	}

	.breadcrumb-item:hover {
		text-decoration: underline;
	}

	/* 文件网格样式 */
	.file-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
		gap: 15px;
	}

	/* 文件列表样式 */
	.file-list {
		background-color: #fff;
		border-radius: 5px;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
		overflow: hidden;
	}

	/* 列表标题行样式 */
	.list-header {
		display: flex;
		background-color: #f5f5f5;
		border-bottom: 1px solid #e5e5e5;
		font-weight: bold;
	}

	/* 列表标题单元格样式 */
	.list-header-cell {
		padding: 12px 15px;
		font-size: 14px;
	}

	/* 列表项样式 */
	.list-item {
		display: flex;
		border-bottom: 1px solid #f0f0f0;
		cursor: pointer;
	}

	.list-item:hover {
		background-color: #fafafa;
	}

	.function-cell {
		visibility: visible;
		/* width: 500px; */
		margin-right: 10px;
		padding: 12px 15px;
		/* background-color: pink; */
		display: flex;
		align-items: center;
	}


	.download-btn {
		background-image: url("/static/icon/download.svg");
		background-size: contain;
		background-repeat: no-repeat;
		background-position: center;
		width: 20px;
		height: 20px;
		border: none;
		background-color: transparent;
		padding: 0;
		margin: 0;
		cursor: pointer;
	}

	.download-btn:active {
		opacity: 0.7;
	}

	/* 覆盖uni-button的伪元素样式 */
	.download-btn:after,
	.delete-btn:after,
	.rename-btn:after {
		content: none !important;
		width: 0 !important;
		height: 0 !important;
		border: none !important;
		transform: none !important;
	}

	.rename-btn {
		background-image: url("/static/icon/rename.svg");
		background-size: contain;
		background-repeat: no-repeat;
		background-position: center;
		width: 24px;
		height: 24px;
		border: none;
		background-color: transparent;
		padding: 0;
		margin-left: 10px;
		cursor: pointer;
	}

	.delete-btn {
		background-image: url("/static/icon/delete.svg");
		background-size: contain;
		background-repeat: no-repeat;
		background-position: center;
		width: 24px;
		height: 24px;
		border: none;
		background-color: transparent;
		padding: 0;
		margin-left: 10px;
		cursor: pointer;
	}

	/* 列表单元格样式 */
	.list-cell {
		padding: 12px 15px;
		font-size: 14px;
		display: flex;
		align-items: center;
	}

	/* 各种列的宽度设置 */
	.name-cell {
		flex: 2;
	}

	.type-cell {
		width: 100px;
	}

	.size-cell {
		width: 100px;
	}

	.date-cell {
		width: 120px;
	}

	/* 搜索图标样式 */
	.search-icon {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.search-icon image {
		width: 20px;
		height: 20px;
	}

	/* 列表视图中的小图标样式 */
	.file-icon-small {
		font-size: 20px;
		margin-right: 10px;
	}

	/* 选中状态的样式 */
	.list-item.selected {
		background-color: #e3f2fd;
	}

	.file-item.selected {
		border: 2px solid #1989fa;
	}

	.file-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 15px;
		background-color: #fff;
		border-radius: 5px;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
		cursor: pointer;
		text-align: center;
	}

	/* 下载按钮样式 - 网格视图 */




	/* 下载按钮样式 - 列表视图 */
	.download-btn-small {
		padding: 3px 8px;
		background-color: #4CAF50;
		color: white;
		border: none;
		border-radius: 3px;
		cursor: pointer;
		font-size: 12px;
		width: 50px;
	}

	.download-btn-small:hover {
		background-color: #45a049;
	}

	/* 下载列样式 - 列表视图 */
	.download-cell {
		width: 70px;
		justify-content: center;
	}

	.file-item:hover {
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
	}

	.file-icon-large {
		font-size: 48px;
		margin-bottom: 10px;
	}

	.file-name {
		font-size: 14px;
		margin-bottom: 5px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		max-width: 100%;
	}

	.file-size {
		font-size: 12px;
		color: #999;
	}

	/* 文件详情样式 */
	.file-details {
		position: absolute;
		top: 20px;
		right: 20px;
		width: 300px;
		background-color: #fff;
		border-radius: 5px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
		overflow: hidden;
	}

	.details-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		background-color: #f5f5f5;
		border-bottom: 1px solid #e5e5e5;
	}

	.details-title {
		font-weight: bold;
	}

	.details-close {
		cursor: pointer;
		font-size: 18px;
	}

	.details-content {
		padding: 15px;
	}

	.detail-item {
		display: block;
		margin-bottom: 10px;
		font-size: 14px;
	}

	.details-actions {
		display: flex;
		gap: 10px;
		padding: 15px;
		border-top: 1px solid #e5e5e5;
	}

	.action-button {
		flex: 1;
		padding: 8px;
		background-color: #f5f5f5;
		border: 1px solid #e5e5e5;
		border-radius: 5px;
		cursor: pointer;
		font-size: 14px;
	}

	.action-button:hover {
		background-color: #e5e5e5;
	}

	/* 管理员按钮样式 */
	.admin-button {
		position: absolute;
		top: 10px;
		right: 20px;
		padding: 5px 10px;
		color: #1989fa;
		cursor: pointer;
		font-size: 14px;
	}

	/* 新建文件夹弹窗样式 */
	.rename-dialog-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}

	.rename-dialog {
		background-color: #fff;
		border-radius: 5px;
		padding: 20px;
		width: 300px;
	}

	.dialog-title {
		display: block;
		margin-bottom: 15px;
		font-weight: bold;
		font-size: 16px;
	}

	.dialog-input {
		width: 95%;
		padding: 10px;
		border: 1px solid #e5e5e5;
		border-radius: 5px;
		margin-bottom: 15px;
		size: 30;
	}

	.dialog-buttons {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
	}

	.dialog-button {
		padding: 8px 16px;
		background-color: #f5f5f5;
		border: 1px solid #e5e5e5;
		border-radius: 5px;
		cursor: pointer;
	}

	.dialog-button.confirm {
		background-color: #1989fa;
		color: white;
		border-color: #1989fa;
	}

	/* 上传进度对话框样式 */
	.upload-dialog-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.upload-dialog {
		background-color: #fff;
		border-radius: 8px;
		width: 500px;
		max-width: 90vw;
		max-height: 80vh;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
	}

	.upload-dialog-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px 20px;
		background-color: #f5f5f5;
		border-bottom: 1px solid #e5e5e5;
	}

	.upload-dialog-title {
		font-weight: bold;
		font-size: 16px;
	}

	.upload-dialog-close {
		font-size: 20px;
		cursor: pointer;
		color: #999;
	}

	.upload-dialog-close:hover {
		color: #333;
	}

	.upload-dialog-content {
		flex: 1;
		padding: 20px;
		overflow-y: auto;
	}

	/* 总体进度样式 */
	.overall-progress {
		margin-bottom: 20px;
	}

	.progress-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10px;
		font-size: 14px;
	}

	.progress-bar {
		height: 10px;
		background-color: #e5e5e5;
		border-radius: 5px;
		overflow: hidden;
		margin-bottom: 5px;
	}

	.progress-fill {
		height: 100%;
		background-color: #4CAF50;
		transition: width 0.3s ease;
	}

	.size-info {
		text-align: right;
		font-size: 12px;
		color: #666;
	}

	/* 文件进度列表样式 */
	.file-progress-list {
		max-height: 300px;
		overflow-y: auto;
	}

	.file-progress-item {
		margin-bottom: 15px;
		padding-bottom: 15px;
		border-bottom: 1px solid #f0f0f0;
	}

	.file-progress-item:last-child {
		border-bottom: none;
		margin-bottom: 0;
		padding-bottom: 0;
	}

	.file-info {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
	}

	.file-icon {
		font-size: 20px;
		margin-right: 10px;
	}

	.file-name {
		flex: 1;
		font-size: 14px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.file-size-small {
		font-size: 12px;
		color: #999;
		margin-left: 10px;
	}

	.file-progress {
		display: flex;
		align-items: center;
	}

	.progress-bar-small {
		flex: 1;
		height: 6px;
		background-color: #e5e5e5;
		border-radius: 3px;
		overflow: hidden;
		margin-right: 10px;
	}

	.progress-fill-small {
		height: 100%;
		background-color: #4CAF50;
		transition: width 0.3s ease;
	}

	.progress-fill-small.progress-error {
		background-color: #f44336;
	}

	.progress-fill-small.progress-success {
		background-color: #4CAF50;
	}

	.progress-text {
		width: 40px;
		text-align: right;
		font-size: 12px;
		color: #666;
	}

	.status-icon {
		margin-left: 5px;
		font-size: 14px;
		color: #4CAF50;
	}

	.status-icon.error {
		color: #f44336;
	}

	/* 对话框底部样式 */
	.upload-dialog-footer {
		display: flex;
		justify-content: flex-end;
		padding: 15px 20px;
		background-color: #f5f5f5;
		border-top: 1px solid #e5e5e5;
	}

	.cancel-button {
		padding: 8px 20px;
		background-color: #f44336;
		color: white;
		border: none;
		border-radius: 5px;
		cursor: pointer;
		font-size: 14px;
	}

	.cancel-button:hover {
		opacity: 0.8;
	}

	.close-button {
		padding: 8px 20px;
		background-color: #1989fa;
		color: white;
		border: none;
		border-radius: 5px;
		cursor: pointer;
		font-size: 14px;
	}

	.close-button:hover {
		opacity: 0.8;
	}
</style>